<?php

class Upload extends CI_Controller {

	function __construct()
	{
		parent::__construct();
		$this->load->helper(array('form', 'url'));
	}

	function index()
	{
		$this->load->view('upload_form', array('error' => ' ' ));
	}
	
	function submit_diary(){
		$this->load->model('Message_model');
		
 
		
	}
	
	/**
	 * 
	 * Insert a diary
	 */
	function submit_photo()
	{
		$this->load->model(array('Photo_model','Location_model'));
		
		// uploading a photo
		if(count($_FILES)>0)
		{
			$title = $_POST['title'];
			$takenlocation = $_POST['takenlocation'];
			
			$location_info = $this->Location_model->search_location($takenlocation,0,1);
			if(count($location_info)==0){
				$location_id = 0;
			}else{
				$location_id = $location_info[0]['l_id'];
			}
			
			$u_name = get_cookie('username');
			$p_access = $_POST['access'];
				
			
			$filename = $this->do_upload();
			
			if($filename == 0){//upload fail;
				$output .= 	$this->smarty->view('js/jump_to.tpl',array("href"=>'index.php'),true);
				$this->output->set_output($output);
				return false;
			}
			
			$takentime = get_takentime($filename); // get takentime from exif
			
			$this->Photo_model->create_photo($title , $takentime , $location_id , $u_name, $p_access);
		}
		else{ //upload fail;
			$output .= 	$this->smarty->view('js/jump_to.tpl',array("href"=>'index.php'),true);
			$this->output->set_output($output);
			return false;
		}
		
	}
	
	/** 
	 * store a photo and return id
	 * @return filename if false $id if success
	 * **/
	function do_upload()
	{
		$id = intval($this->Photo_model->get_max_id()) + 1; 
		
		$config['upload_path'] = UPLOAD_PATH;
		$config['allowed_types'] = 'jpg';
		$config['max_size']	= '100';
		$config['max_width'] = '1024';
		$config['max_height'] = '768';
		
	
		$filename = $id.".jpg";
		$config['file_name'] = $filename;
		 
		$this->load->library('upload', $config);
		
		// Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class:
		$this->upload->initialize($config);

		if ( ! $this->upload->do_upload("photo"))
		{
			$error = array('error' => $this->upload->display_errors());
			var_dump($error);
			return 0;
 		}
		else
		{
			$data = array('upload_data' => $this->upload->data());
			return $filename;
 		}
		
	}
}
?>